package com.business.user.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.business.common.dto.R;
import com.business.redis.ExpiresTimeEnum;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisUtil;
import com.business.user.annotation.FrequentRequest;
import com.business.user.annotation.TokenPermission;
import com.business.user.entity.Message;
import com.business.user.entity.UserDto;
import com.business.user.service.MessageService;
import com.business.user.utils.PageFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 消息表: 后端controller类
 *
 * @author chenjiehong
 * @date 2019-11-29 14:28:27
 * @since 1.0
 */
@RestController
@RequestMapping(value = "/message")
@TokenPermission
public class MessageController {


    @Autowired
    private MessageService messageServiceImpl;


    /**
     * 新增消息表
     *
     * @param message
     * @date 2019-11-29 14:28:27
     */
    @PostMapping("/add")
    @ResponseBody
    @FrequentRequest(5)//控制频繁操作 一分钟内可以操作5次
    public R add(@RequestBody Message message, UserDto user) {
        message.setFromUserId(user.getId());
        message.setType(1);//留言
        return R.success(messageServiceImpl.add(message));
    }


    /**
     * 查询消息表
     *
     * @param params
     * @date 2019-11-29 14:28:27
     */
    @PostMapping("/query")
    @ResponseBody
    public R query(@RequestBody JSONObject params) {
        Integer id = params.getInteger("id");
        String key = String.format(RedisKeyConstant.MESSAGE_QUERY, id);
        Message message = null;
        if (RedisUtil.hasKey(key)) {
            message = (Message) RedisUtil.getObject(key, Message.class);
        } else {
            message = messageServiceImpl.query(id);
            RedisUtil.setValue(key, message, ExpiresTimeEnum.LEVEL_2.getExpiresTime());
        }
        return R.success(message);
    }


    /**
     * 分页查询消息表
     *
     * @param params
     * @date 2019-11-29 14:28:27
     */
    @PostMapping("/queryPage")
    @ResponseBody
    @TokenPermission
    public R queryPage(@RequestBody JSONObject params, UserDto userDto) {
        Page<Message> page = new PageFactory<Message>().defaultPage(params);
        Integer type = params.getIntValue("type");
        Integer isAll = params.getInteger("isAll");
        return R.success(messageServiceImpl.queryPage(page, userDto.getId(), type, isAll));
    }


    /**
     * 分页查询消息表
     *
     * @param params
     * @date 2019-11-29 14:28:27
     */
    @PostMapping("/queryPageByOwn")
    @ResponseBody
    @TokenPermission
    public R queryPageByOwn(@RequestBody JSONObject params, UserDto userDto) {
        Page<Message> page = new PageFactory<Message>().defaultPage(params);
        Integer type = params.getIntValue("type");
        Integer isAll = params.getInteger("isAll");
        return R.success(messageServiceImpl.queryPageByOwn(page, userDto.getId(), type, isAll));
    }


    /**
     * 更新消息表
     *
     * @param params
     * @date 2019-11-29 14:28:27
     */
    @PostMapping("/updateState")
    @ResponseBody
    public R updateState(@RequestBody JSONObject params, UserDto user) {
        Integer id = params.getIntValue("id");
        Integer r = messageServiceImpl.updateState(id, 1);
        if (r > 0) {
            Set<String> keys = new HashSet<>();
            String key = String.format(RedisKeyConstant.MESSAGE_QUERY, id);
            String key2 = String.format(RedisKeyConstant.MESSAGE_COUNT, user.getId());
            String key3 = String.format(RedisKeyConstant.MESSAGE_COUNT_BY_TYPE, user.getId());
            keys.add(key);
            keys.add(key2);
            keys.add(key3);

            RedisUtil.delValue(keys);
        }
        return R.success(r);
    }

    /**
     * 更新消息表
     *
     * @param params
     * @date 2019-11-29 14:28:27
     */
    @PostMapping("/updateList")
    @ResponseBody
    public R updateList(@RequestBody JSONObject params, UserDto user) {
        JSONArray jsonArray = params.getJSONArray("ids");
        Set<String> keys = new HashSet<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            int id = jsonArray.getIntValue(i);
            Integer r = messageServiceImpl.updateState(id, 1);
            if (r > 0) {
                String key = String.format(RedisKeyConstant.MESSAGE_QUERY, id);
                String key2 = String.format(RedisKeyConstant.MESSAGE_COUNT, user.getId());
                String key3 = String.format(RedisKeyConstant.MESSAGE_COUNT_BY_TYPE, user.getId());
                keys.add(key);
                keys.add(key2);
                keys.add(key3);
            }
        }
        if (keys.size() > 0) {
            RedisUtil.delValue(keys);
        }
        return R.success();
    }

    /**
     * 查询未读总数
     *
     * @param user
     * @date 2019-11-29 14:28:27
     */
    @PostMapping("/getCount")
    @ResponseBody
    @TokenPermission
    public R getCount(UserDto user) {
        String key = String.format(RedisKeyConstant.MESSAGE_COUNT, user.getId());
        Integer count = null;
        if (RedisUtil.hasKey(key)) {
            count = (Integer) RedisUtil.getValue(key);
        } else {
            count = messageServiceImpl.getCount(user.getId());
            RedisUtil.setValue(key, count, ExpiresTimeEnum.LEVEL_2.getExpiresTime());
        }
        return R.success(count);
    }

    /**
     * 查询未读总数
     *
     * @param user
     * @date 2019-11-29 14:28:27
     */
    @PostMapping("/getCountByType")
    @ResponseBody
    @TokenPermission
    public R getCountByType(UserDto user) {
        String key = String.format(RedisKeyConstant.MESSAGE_COUNT_BY_TYPE, user.getId());
        Map<String, Integer> resultMap = new HashMap<>();
        if (RedisUtil.hasKey(key)) {
            Set<String> keys = RedisUtil.getHashKeys(key);
            Iterator<String> iterator = keys.iterator();
            while (iterator.hasNext()) {
                String type = iterator.next();
                resultMap.put(type, Integer.parseInt(RedisUtil.getHashValue(key, type) + ""));
            }
        } else {
            List<Map<String, Integer>> mapList = messageServiceImpl.getCountByType(user.getId());
            for (Map<String, Integer> map : mapList) {
                Integer type = map.get("type");
                Integer value = map.get("value");
                resultMap.put(type + "", value);
                RedisUtil.setHashValue(key, type + "", value);
            }
            RedisUtil.expire(key, ExpiresTimeEnum.LEVEL_1.getExpiresTime());
        }
        return R.success(resultMap);
    }

}